const fs = require('fs')
const path = require('path')
const rimraf = require('rimraf')
const merge = require('webpack-merge')
const tsImportPluginFactory = require('ts-import-plugin')
const { resolve } = require('./build/utils')
// eslint-disable-next-line import/no-extraneous-dependencies
const cssEnv = require('postcss-preset-env')
const pxtorem = require('postcss-pxtorem')
const dayjs = require('dayjs');
const pkg = require('./package.json');

const { envConfig, targetConfig } = require('./boot')

// 正式环境和预发布环境先删除dist目录
if (['prod', 'prior'].includes(envConfig.type)) {
  rimraf.sync('./dist')
}

process.env.VUE_APP_PK_VERSION = pkg.version;
process.env.VUE_APP_BUILD_DATE = dayjs().format('YYYY-MM-DD HH:mm:ss');

const BASE_PATH = resolve('src/pages')

// 扫描指定文件夹
const scanDir = (path) => {
  let pages = fs.readdirSync(path)
  if (targetConfig.pageList.listMode === 'black') {
    return pages.filter((v) => !targetConfig.pageList.blackList.includes(v))
  }
  if (targetConfig.pageList.listMode === 'white') {
    pages = pages.filter((v) => targetConfig.pageList.whiteList.includes(v))
  }
  return pages
}

const pages = {}

const pageNames = scanDir(BASE_PATH)

pageNames.forEach((v) => {
  const page_path = path.join(BASE_PATH, v)
  if (fs.lstatSync(page_path).isDirectory()) {
    pages[v] = {
      entry: `src/pages/${v}/index.ts`,
      template: `template/${envConfig.template}`,
      filename: `${v}.html`,
      title: '',
    }
  }
})

/** @type import('@vue/cli-service').ProjectOptions */
module.exports = {
  outputDir: resolve(`dist${targetConfig.dir || ''}`),
  assetsDir: 'static',
  publicPath: targetConfig.dir,
  productionSourceMap: false, // 打包时不打包调试帮助文件
  parallel: false, // 关闭以修复打包后按需引入的样式丢失
  lintOnSave: true,
  devServer: {
    port: 4040,
  },
  pages,
  css: {
    // 打包模式为外置库时 内联样式文件
    loaderOptions: {
      postcss: {
        plugins: [
          // require('autoprefixer')({
          //   overrideBrowserslist: ['> 1% in CN', 'last 2 versions', 'ios >= 8', 'not ie <= 8']
          // })
          cssEnv({
            preserve: true,
            importFrom: ['src/assets/style/variables.css'],
            /**
             * NOTE color-mod方法的提案已经被rejected，csstool已将其stage定义改成了-1
             * {@see https://github.com/csstools/cssdb/commit/96bb8e8547a946dcbc29b866ac13330fed6ca04b}
             * {@see https://www.w3.org/TR/2016/WD-css-color-4-20160705/#funcdef-color-mod}
             */
            stage: -1,
          }),
          pxtorem({
            rootValue: 50,
            propList: ['*'],
            exclude:/node_modules|eight_electrodes_report_download/i
            // selectorBlackList: [/^\.van-/],
          }),
        ],
      },
    },
  },
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      // config.optimization.splitChunks = {
      //   cacheGroups: {
      //     axios: {
      //       test: /\/axios\//,
      //       minChunks: 1,
      //       minSize: 0,
      //       name: 'axios',
      //       chunks: 'all',
      //       priority: -1
      //     },
      //     bluebird: {
      //       test: /\/bluebird\//,
      //       minChunks: 1,
      //       minSize: 0,
      //       name: 'bluebird',
      //       chunks: 'all',
      //       priority: -1
      //     },
      //     vant: {
      //       test: /\/vant\//,
      //       minChunks: 1,
      //       minSize: 0,
      //       name: 'vant',
      //       chunks: 'all',
      //       priority: -9
      //     },
      //     vue: {
      //       test: /\/vue\//,
      //       minChunks: 1,
      //       minSize: 0,
      //       name: 'vue',
      //       chunks: 'all',
      //       priority: -10
      //     }
      //   }
      // }
    }

    if (envConfig.type === 'prod') {
      // 清除console.log语句
      config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
    }

    return {
      output: {
        libraryExport: 'default',
      },
      devtool: 'source-map',
      performance: {
        hints: false,
      },
      resolve: {
        alias: {
          '@': resolve('src'),
          '@@': resolve(''),
        },
      },
    }
  },
  chainWebpack: (config) => {
    // config.module
    //     .rule('webConfig-loader')
    //     .test(/\.vue$/)
    //     .use()
    //     .loader(resolve('./loader/webConfig/index.js'))
    //     .options({
    //       name: webConfigFile,
    //       defaultFile: 'Renpho'
    //     })
    //     .end()
    // config.module
    //   .rule('ts')
    //   .use('ts-loader')
    //   .tap(options => {
    //     options = merge(options, {
    //       transpileOnly: true,
    //       getCustomTransformers: () => ({
    //         before: [
    //           tsImportPluginFactory({
    //             libraryName: 'vant',
    //             libraryDirectory: 'es',
    //             style: name => `${name}/style`
    //           })
    //         ]
    //       }),
    //       compilerOptions: {
    //         module: 'es2015'
    //       }
    //     })
    //     return options
    //   })
  },
}
